﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using TekaMUD.Engine.Framework;
using TekaMUD.Engine.Persistence;

namespace TekaMUD.Engine.Workers
{
	public class WorkerThreadStorage : WorkerThread, ISingleWorker
	{
		public WorkerThreadStorage(TimeSpan period) : base("Storage Thread", period)
		{
			if (period.TotalSeconds < 1)
				throw new ArgumentOutOfRangeException("Period too short.");
		}

		protected override void Run()
		{
			while (!Terminated)
			{
				// Sleeps for a while.
				Thread.Sleep(Period);

				if(Terminated)
					goto cleanup;

				Locks.StorageLock.EnterWriteLock();
				Logger.LogInfo("Storage Thread starting...");

				Storage.UpdateWorld();
				
				Locks.StorageLock.ExitWriteLock();
				Logger.LogInfo("Storage Thread finished.");
				LastRun = DateTime.Now;
			}

		cleanup:
			Logger.LogInfo("[Thread] Storage worker terminated.");
		}
	}
}
